package com.northpool.operator.cicd.ssh;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(
        ref = "SshFileDelOperator",
        name = "sftp文件删除",
        description = "sftp文件删除算子",
        version = "1.0.0"
)
public class SshFileDelOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "host", name = "主机", desc = "主机IP或域名，如：10.80.9.11", required = true),
            @InputParam(ref = "port", name = "端口", desc = "SSH服务端口，如：22", value = "22", type = TypeEnum.NUMBER),
            @InputParam(ref = "user", name = "用户名", desc = "登录用户名，如：test", required = true),
            @InputParam(ref = "pass", name = "密码", desc = "登录密码，如：password", required = true, type = TypeEnum.SECRET),
            @InputParam(ref = "file", name = "文件路径", desc = "文件路径，如：/data/temp/test.txt", required = true)
    })
    public SshFileDelOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(SshFileDelOperator.class, TestParamBuilder.aBuilder()
                .param("host", "192.168.5.11")
                .param("port", "22")
                .param("user", "root")
                .param("pass", "950519")
                .param("file", "/root/2023DLTB.shp")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String host = paramTool.getStr("host");
        int port = paramTool.getNumber("port").intValue();
        String user = paramTool.getStr("user");
        String pass = paramTool.getStr("pass");
        String filePath = paramTool.getStr("file");

        JschUtils jschUtils = new JschUtils();
        try {
            jschUtils.connect(user, pass, host, port);

            String dir = StrUtil.subBefore(filePath, "/", true);
            String file = StrUtil.subAfter(filePath, "/", true);

            jschUtils.delete(dir, file);
        } catch (Exception e) {
            String stacktrace = ExceptionUtil.stacktraceToString(e);
            this.error("远程文件删除失败，错误堆栈: {}", stacktrace);
        } finally {
            jschUtils.close();
        }

    }
}
